package com.cn.newetv.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.cn.newetv.po.SegDO;
import com.cn.newetv.po.VideoDO;

public class ParseYouKuFilmParam {
	static String interString = "pid=143f8dcdfe8db081&guid=&ver=2.1&network=&format=1&rt=2";
	private static String filetype = "mp4";
	public static String converStreamToString(InputStream inputstream) throws Exception {
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream));
        StringBuilder stringbuilder = new StringBuilder();
        String s = null;
        do {
	        s = bufferedreader.readLine();
	        stringbuilder.append((new StringBuilder(String.valueOf(s))).toString());
        } while(s != null);
        
        try {
        	inputstream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return stringbuilder.toString();
	}
	
	public static JSONObject transToJson(String strJson) throws Exception {
		if(strJson == null || strJson.length() == 0)
			return null;
		JSONObject jsonobj = new JSONObject(strJson);
		return jsonobj;
	}
	
	public static String connectAPI(String strurl) throws Exception {
		int resCode = 0;
		URL url = new URL(strurl);
		URLConnection urlConnection = url.openConnection();
		HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
		httpURLConnection.setAllowUserInteraction(false);
        httpURLConnection.setInstanceFollowRedirects(true);
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("User-Agent", "");
        httpURLConnection.connect();
        resCode = httpURLConnection.getResponseCode();
        if (resCode != 200)
        	return null;
        else 
        	return converStreamToString(httpURLConnection.getInputStream());
        
	}
	
	public static VideoDO getVideoInfo(String videoId, String type) {
		try {
			Log.d("debug", "videoId:"+videoId+" type:"+type);
			filetype = type;
			String url = constructURL(videoId);
			String strData = connectAPI(url);
			JSONObject json = transToJson(strData);
			System.out.println(strData);
			return constructDO(json);
		} catch (Exception e) {
			Log.e("study", e.getMessage());
		}
		return null;
	}
	
	public static VideoDO constructDO(JSONObject json) throws Exception {
		VideoDO videoDO = new VideoDO();
		String type = filetype;
		JSONArray array = json.getJSONArray("data");
		JSONObject data = array.getJSONObject(0);
		double seed = data.getDouble("seed");
		System.out.println(seed);
		
		videoDO.setVname(data.getString("title"));
		videoDO.setTotalseconds(data.getInt("seconds"));
		
		JSONObject streamfileids = data.getJSONObject("streamfileids");
		String sfileid  = streamfileids.getString(type);
		System.out.println(sfileid);
		String fileid = getFileID(sfileid,seed);
		System.out.println(fileid);
		String sid = genSid();
		System.out.println(sid);
		
		JSONObject segs = data.getJSONObject("segs");
		JSONArray typedata = segs.getJSONArray(type);
		
		List<SegDO> seglist = new ArrayList<SegDO>();
		
		for (int i = 0; i < typedata.length(); i++) {
			JSONObject seg = typedata.getJSONObject(i);
			//System.out.println(seg);
			
			String k = seg.getString("k");
			String k2 = seg.getString("k2");
			String no = seg.getString("no");
			no = Integer.toHexString(Byte.valueOf(no) & 0xFF);
			if(no.length()<2)
				no = "0"+no;
			no = no.toUpperCase();
			
			StringBuffer segfileid = new StringBuffer();
			segfileid.append(fileid.substring(0, 8));
			segfileid.append(no);
			segfileid.append(fileid.substring(10));
			
			StringBuffer surl = new StringBuffer("http://f.youku.com/player/getFlvPath/sid/");
			surl.append(sid);
			surl.append("_");
			surl.append(no);
			surl.append("/st/");
			surl.append(type);
			surl.append("/fileid/");
			surl.append(segfileid.toString());
			surl.append("fileid");
			surl.append("?");
			surl.append("K=");
			surl.append(k);
			surl.append(",");
			surl.append("k2=");
			surl.append(k2);
			System.out.println(surl.toString());
			
			SegDO segDO = new SegDO();
			segDO.setId(seg.getInt("no"));
			segDO.setSeconds(seg.getInt("seconds"));
			segDO.setSize(seg.getInt("size"));
			segDO.setUrl(surl.toString());
			seglist.add(segDO);
		}
		videoDO.setSegs(seglist);
		return videoDO;
/*		VideoDO videoDO = new VideoDO();
		List<SegDO> segs = new ArrayList<SegDO>();
		JSONObject streamPadMp4 = json.getJSONObject("results").getJSONObject("streamPadMp4");
		videoDO.setTotalseconds(streamPadMp4.getInt("totalseconds"));
		videoDO.setVname(json.getJSONObject("results").getString("showname"));
		JSONArray array = streamPadMp4.getJSONArray("segs");
		
		for (int i = 0; i < array.length(); i++) {
			JSONObject js = array.getJSONObject(i);
			SegDO segDO = new SegDO();
			segDO.setId(js.getInt("id"));
			segDO.setSeconds(js.getInt("seconds"));
			segDO.setSize(js.getInt("size"));
			segDO.setUrl(js.getString("url"));
			segs.add(segDO);
		}
		videoDO.setSegs(segs);
		return videoDO;
		*/
	}
	
	public static String constructURL(String videoId) {
		return (new StringBuilder("http://v.youku.com/player/getPlayList/VideoIDS/")).append(videoId).toString();
	}
	
	private static String getFileID(String fileid, double seed) {
		String mixed = getFileIDMixString(seed);
		String[] ids = fileid.split("\\*");
		StringBuilder realId = new StringBuilder();
		int idx;
		for (int i = 0; i < ids.length; i++) {
			idx = Integer.parseInt(ids[i]);
			realId.append(mixed.charAt(idx));
		}
		return realId.toString();
	}

	private static String genSid() {
		int i1 = (int) (1000 + Math.floor(Math.random() * 999));
		int i2 = (int) (1000 + Math.floor(Math.random() * 9000));
		return System.currentTimeMillis() + "" + i1 + "" + i2;
	}

	private static String getFileIDMixString(double seed) {
		StringBuilder mixed = new StringBuilder();
		StringBuilder source = new StringBuilder(
				"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\:._-1234567890");
		int index, len = source.length();
		for (int i = 0; i < len; ++i) {
			seed = (seed * 211 + 30031) % 65536;
			index = (int) Math.floor(seed / 65536 * source.length());
			mixed.append(source.charAt(index));
			source.deleteCharAt(index);
		}

		return mixed.toString();
	}
}
